package org.noidler.demo;

import com.mongodb.MongoClientSettings;
import com.mongodb.ServerAddress;
import com.mongodb.client.*;
import com.mongodb.client.model.Filters;
import org.bson.Document;
import org.bson.codecs.configuration.CodecRegistries;
import org.bson.codecs.configuration.CodecRegistry;
import org.bson.codecs.pojo.PojoCodecProvider;
import org.bson.conversions.Bson;
import org.noidler.model.AnyThing;

import java.util.*;

import static org.bson.codecs.configuration.CodecRegistries.fromRegistries;

public class MongoDb {
//    MongoClient mongoClient=null;

    public static void main(String[] args) {
//      m1();

        m2();
    }

    private static void m1() {
        ServerAddress seed1 = new ServerAddress("localhost", 27017);
        MongoClientSettings settings = MongoClientSettings.builder()
                .applyToClusterSettings(builder ->
                        builder.hosts(Collections.singletonList(seed1)))
                .build();
        MongoClient mongoClient = MongoClients.create(settings);
        MongoDatabase controller = mongoClient.getDatabase("any");
        MongoCollection<Document> BASEDB = controller.getCollection("base");
        BASEDB.insertOne(new Document("name", "MongoDB"));
        for (int i = 0; i < 10; i++) {
            String jsonString = toJsonString(gen());
            BASEDB.insertOne(Document.parse(jsonString));
        }
        Bson filters = Filters.eq("id", "a58acbdd-9ff5-449d-9709-6931a8592558");
        FindIterable<Document> alarms = BASEDB.find(filters, Document.class);
        System.out.println(alarms.first());
        mongoClient.close();
    }

    /**
     * PojoCodecProvider 无法正常工作，可以插入数据 无法查询，
     * 调整MongoDB 驱动为5.2可用
     */
    public static void m2() {
        CodecRegistry codecRegistry = CodecRegistries.fromProviders(
                PojoCodecProvider.builder().register("org.noidler.model").build()
        );
//        PojoCodecProvider pojoCodecProvider = PojoCodecProvider.builder().register("com.example").build();

        System.out.println("==================================!");
        ServerAddress seed1 = new ServerAddress("localhost", 27017);
        MongoClientSettings settings = MongoClientSettings.builder()
                .codecRegistry(fromRegistries(MongoClientSettings.getDefaultCodecRegistry(), codecRegistry))
                .applyToClusterSettings(builder ->
                        builder.hosts(Collections.singletonList(seed1)))
                .build();
        MongoClient mongoClient = MongoClients.create(settings);
        MongoDatabase controller = mongoClient.getDatabase("controller");
        MongoCollection<AnyThing> BASEDB = controller.getCollection("base", AnyThing.class);
        List<String> ids = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            String id = Objects.requireNonNull(BASEDB.insertOne(gen()).getInsertedId()).asString().getValue();
            ids.add(id);
        }
        Bson filters = Filters.in("_id", ids);
        FindIterable<AnyThing> alarms = BASEDB.find(filters).batchSize(ids.size());
        try (MongoCursor<AnyThing> cursor = alarms.cursor()) {
            while (cursor.hasNext()) {
                System.out.println("==================================!");
                AnyThing alarm = cursor.next();
                System.out.println(alarm);
            }
        }
        mongoClient.close();


    }

    private static String toJsonString(AnyThing gen) {
        return JSONUtils.toJsonString(gen);
    }

    public static AnyThing gen() {
        AnythingBuilder builder = AnythingBuilder.builder();
        UUID uuid = UUID.randomUUID();
        Map<String, Object> params = new HashMap<>();
        params.put("param1", "value1");
        params.put("param2", "value2");
        return builder.withCode(uuid.toString())
                .withId(uuid.toString())
                .withConditionType("condi" + uuid.toString())
                .withDescription("description" + uuid.toString())
                .withName(getRandomName())
                .withParams(params).build();
    }
    //一个生成随机名称的函数，20个名称内随机
    public static String getRandomName() {
        String[] names = {"Alice", "Bob", "Charlie", "David", "Eve", "Frank", "Grace", "Hannah", "Ivy", "Jack", "Kate", "Liam", "Mia", "Nancy", "Oliver", "Penny", "Quinn", "Rachel", "Sophia", "Tom"};
        Random random = new Random();
        return names[random.nextInt(names.length)];
    }
}
